export const applyMixin = {
  data () {
    return {
      isApplyBack: false,
      instanceId: null,
      isAllowApply: false
    }
  },
  computed: {
    query () {
      return this.$attrs?.tab?.query
    }
  }
}

export const TableColumnSortMixin = {
  data () {
    return {
      showFields: []
    }
  },
  computed: {
    key () {
      return this.customKey || this.$options.name
    },
    username () {
      return this.$store.state.userInfo.username
    }
  },
  watch: {
    showFields (val) {
      // 缓存showFields
      const showFieldsObj = this.$ls.getObj(`${this.username}-showFieldsObj`, {})
      this.$ls.set(`${this.username}-showFieldsObj`, { ...showFieldsObj, [this.key]: val })
    }
  },
  created () {
    // this.showFields = this.getLatestShowFields()
  },
  methods: {
    /**
     * 对比columnProps，在oldShowFields的基础上获取最新的showFields
     * @param key 从localStorage获取对应值的key，默认使用组件名this.$options.name
     * @param newColumns 本次的（即最新的）表格数据，默认使用this.columns
     * @return {*|Array} showFields
     */
    getLatestShowFields (newColumns = this.columns) {
      const { key, username } = this

      let showFields = this.$ls.getObj(`${username}-showFieldsObj`, {})[key] || []

      const oldColumnPropsObj = this.$ls.getObj(`${username}-columnPropsObj`, {})
      const oldColumnProps = oldColumnPropsObj[key]
      const newColumnProps = newColumns.map(item => item.prop).filter(item => item)

      if (oldColumnProps) { // 存在缓存的columns
        // 与newColumnProps对比，找出新增和删除的prop（修改prop本质上也是新增删除），更新到showFields
        const addProps = newColumnProps.filter(prop => !oldColumnProps.includes(prop))
        const reduceProps = oldColumnProps.filter(prop => !newColumnProps.includes(prop))

        if (addProps.length || reduceProps.length) {
          if (addProps.length) showFields = [...showFields, ...addProps] // 暂时不考虑新增字段的顺序
          if (reduceProps.length) showFields = showFields.filter(field => !reduceProps.includes(field))
          this.$ls.set(`${username}-columnPropsObj`, { ...oldColumnPropsObj, [key]: newColumnProps })
        }
      } else { // 不存在缓存的columns，对应页面第一次加载的情况
        showFields = newColumnProps
        this.$ls.set(`${username}-columnPropsObj`, { ...oldColumnPropsObj, [key]: newColumnProps })
      }

      return showFields
    }
  }
}
